package com.example.rabbitmq.demo1_modes.producer.mode01_simple;

import com.example.rabbitmq.enums.RabbitmqQueueNamesEnum;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author songyahui
 * @Date 2023/7/6 16:58
 * @Description 生产&&发送消息
 */
public class SimpleProducer {

    public static final String QUEUE_NAME = "hello world";

    //消息发送
    public static void buildMessage() throws IOException, TimeoutException {
        Connection connection = null;
        Channel channel = null;
        try {
            //创建工厂
            ConnectionFactory factory = new ConnectionFactory();
            //工厂IP 连接rabbitmq队列
            factory.setHost("127.0.0.1");
            //设置用户名称
            factory.setUsername("guest");
            //设置密码
            factory.setPassword("guest");
            //创建连接
            connection = factory.newConnection();
            //获取信道
            channel = connection.createChannel();
            //创建队列：
            //    设置队列名称、是否持久化该队列、是否共享队列消息的消费（true：共享消费，false：只有一个消费者消费）、是否自动删除该队列（true：消息用完后自动删除、false：）、其它参数（延迟、死信消息处理用）
//            channel.queueDeclare(RabbitmqQueueNamesEnum.QUEUE_NAME_SIMPLE.queueName, true, false, false, null);
            channel.queueDeclare(RabbitmqQueueNamesEnum.QUEUE_NAME_HELLO.queueName, true, false, false, null);
            //发送消息
            String message = "hello world 你好，世界";

            //消息发送
//            channel.basicPublish("", RabbitmqQueueNamesEnum.QUEUE_NAME_SIMPLE.queueName, null, message.getBytes());
            channel.basicPublish("", RabbitmqQueueNamesEnum.QUEUE_NAME_HELLO.queueName, null, message.getBytes());
        }
        finally{
            channel.close();
            connection.close();
        }
    }
}
